<template>
	<div class="bg">
		<uni-nav-bar :fixed="true" title="消缺登记" background-color="#5C7FF5" status-bar @clickLeft="back" :dark="true"
			left-icon="left">

		</uni-nav-bar>
		<view v-for="(item, index) in num" :key="index">
			<canvas :canvas-id="Canvas + index" style="visibility: hidden; width: 0; height: 0" :style="style"></canvas>
		</view>
		<div class="p50 bgwhite">
			<uni-file-picker multiple limit="9" :sizeType="sizeType" @success="success" @progress="progress"
				@fail="fail" @delete="deletes" @select="select" :del-icon="true" v-model="fileLists">
				<img src="../../static/img/isAdd.png" style="width: 72rpx;height: 60rpx;" alt="">
			</uni-file-picker>
		</div>
		<div class="p30 bgwhite" style="margin-bottom: 20rpx;">
			<div class="infoItem" v-if="rules =='admin' || rules =='administrator'">
				<div class="infoItem_label">消缺人员</div>

				<div class="infoItem_content"><input type="text" maxlength="10" v-model="form.solveName"></div>
			</div>
			<div class="infoItem noboderbottom">
				<div class="infoItem_label">备注</div>
				<div class="infoItem_content"><input v-model="form.solveRemarks" type="text" maxlength="100"></div>
			</div>
		</div>
		<div class="line"></div>

		<div class="addBtn">
			<div class="bts edit" @click="toright">
				提交
			</div>

		</div>

	</div>
</template>

<script>
	import {
		COM_URL,
		IMG_URL
	} from "@/utils/config";
	import {
		findDefectByCode,
		solveDefect
	} from '@/utils/http'
	export default {
		data() {
			return {
				Canvas: "ll_canvas_img",
				type: null,
				num: 0,
				count: -1,
				style: null,
				form: {
					solveRemarks: '',
					code: '',
					solveName: '',
					pic: [],
				},
				rules: "",
				isUse: true,
				fileLists: [],
				fileListsCopy: []

			};
		},
		onShow() {
			this.rules = uni.getStorageSync('userInfo').role

		},
		onLoad(query) {
			this.form.code = query.code

		},
		methods: {
			deletes(val) {
				this.fileListsCopy.splice(val.index, 1)
			},
			back() {
				console.log(22222)
				uni.navigateBack({
					delta: 1 // 默认值是1，表示回退到上一页，如果要回退多级可以设置大于1的数值
				});
				//       if(uni.getStorageSync('userInfo').userName == '消缺员'){
				//                     uni.reLaunch({
				//  url:'/pages/order/index'
				// })
				//                   }else  if(uni.getStorageSync('userInfo').userName == '管理员'){
				//                     uni.reLaunch({
				//  url:'/pages/order/managerIndex'
				// })
				//                   }
			},
			//格式转换
			process_img(src, quality = 0.9, type = "jpg", ratio = 0.9) {
				return new Promise((resolve, reject) => {
					this.count++
					this.num++
					let Canvas = this.Canvas + this.count
					uni.getImageInfo({
						src: src,
						success: (res) => {
							let width = res.width
							let height = res.height
							this.style =
								`margin-top: -${height}px; margin-left: -${width}px; width: ${width}px; height: ${height}px;`
							setTimeout(() => {
								const ctx = uni.createCanvasContext(Canvas, this)
								ctx.clearRect(0, 0, width, height)
								ctx.drawImage(src, 0, 0, width, height)
								ctx.draw(false, () => {
									uni.canvasToTempFilePath({
											width: width,
											height: height,
											destWidth: width * ratio,
											destHeight: height * ratio,
											canvasId: Canvas,
											fileType: type,
											quality: quality,
											success: (res) => {
												// #ifdef H5

												// #endif

												console.log("格式转换成功")
												resolve(res.tempFilePath)
											},
											fail: (err) => {
												console.log("格式转换失败")
												reject(err)
											},
										},
										this
									)
								})
							}, 500)
						},
					})
				})
			},
			//图片压缩
			compress_img(src, size = 500, type = "jpg", ratio = 0.9) {
				return new Promise((resolve, reject) => {
					this.type = type
					this.process_img(src, 0.9, type).then((res) => {
						src = res
						this.compress(src, size, type)
							.then((res) => {
								console.log("压缩成功", res) // 输出压缩后的图片路径
								resolve(res)
							})
							.catch((err) => {
								reject(err)
							})
					})
				})
			},
			compress(src, size = 500, type, ratio = 0.9) {
				return new Promise((resolve, reject) => {
					uni.getFileInfo({
						filePath: src,
						success: (fileInfoRes) => {
							let fileSize = fileInfoRes.size / 1024 // 转换为KB
							console.log("图片大小", fileSize)
							if (fileSize > size) {
								// #ifndef H5
								this.process_img(src, 0.9, type, ratio)
									.then((res) => {
										src = res
										this.compress(src, size)
											.then((res) => {
												resolve(res)
											})
											.catch((err) => {
												reject(err)
											})
									})
									.catch((err) => {
										reject(err)
									})
								// #endif
								// #ifdef H5
								uni.getImageInfo({
									src: src,
									success: (res) => {
										//console.log('压缩前信息', res);
										let canvasWidth = res.width // 图片原始宽度
										let canvasHeight = res.height // 图片原始高度
										//console.log('宽度-',canvasWidth,'高度-',canvasHeight);
										let img = new Image()
										img.src = res.path
										let canvas = document.createElement("canvas")
										let ctx = canvas.getContext("2d")
										// 这里根据要求限制图片宽高
										canvas.width = canvasWidth * ratio
										canvas.height = canvasHeight * ratio
										//console.log('压缩尺寸',canvas.width,canvas.height)
										ctx.drawImage(img, 0, 0, canvas.width, canvas
											.height)
										//toBlob()方法创造Blob对象，用以展示canvas上的图片
										let type_h5
										if (this.type == "jpg") type_h5 = "image/jpeg"
										else if (this.type == "png") type_h5 = "image/png"
										else if (this.type == "webp") type_h5 =
											"image/webp"
										canvas.toBlob(
											(fileSrc) => {
												let imgSrc = window.URL
													.createObjectURL(fileSrc)
												//console.log('压缩后的blob路径', imgSrc);
												this.compress(imgSrc, size).then((
													res) => {
													resolve(res)
												})
											},
											type_h5,
											0.9
										) //默认'image/png' 建议'image/jpeg' 扩展image/webp(大部分浏览器支持),其他未知
									},
								})
								// #endif
							} else {
								resolve(src)
							}
						},
					})
				})
			},
			// 上传图片
			async select(val) {
				var that = this
				uni.showLoading({
					title: "加载中",
					mask: true
				});
				for (let i = 0; i < val.tempFilePaths.length; i++) {
					await this.doSomething(val.tempFilePaths[i]).then(res => {
						if (i == val.tempFilePaths.length - 1) {
							uni.hideLoading();
						}
					})
				}
			},
			async doSomething(item) {
				var that = this;

				return new Promise((resolve, reject) => {

					uni.uploadFile({
						url: `${COM_URL}/manager/uploadPic`, //后端用于处理图片并返回图片地址的接口
						filePath: item,
						header: {
							token: uni.getStorageSync("token"),
						},
						name: "file",
						success: (res) => {
							let data = JSON.parse(res.data)
							if (data.code == '0') {
								that.fileListsCopy.push({
									url: `${IMG_URL}${data.result.path}`,
									path: data.result.path,
									ids: new Date().getTime().toString(),
									name: new Date().getTime().toString(),
									extname: "png",
								});
								resolve(item)

							} else {
								resolve(item)
								setTimeout(() => {
									uni.hideLoading();

								}, 1500)
							}
						},
						fail: () => {
							setTimeout(() => {
								uni.hideLoading();

							}, 1500)
						},
					});
				});


			},

			// 消缺
			toright() {
				if (this.isUse) {
					this.isUse = false
					const regex = /[\u4e00-\u9fa5a-zA-Z0-9\p{P}]+$/u;
					if (this.rules == 'admin' || this.rules == 'admin') {
						if (!this.form.solveName) {
							this.isUse = true

							wx.showToast({
								title: '请输入姓名',
								icon: 'none'
							})
							return
						}
						if (!regex.test(this.form.solveName)) {
							this.isUse = true

							wx.showToast({
								title: '请输入正确的姓名格式',
								icon: 'none'
							})
							return
						}
					} else {
						this.form.solveName = uni.getStorageSync('account')
					}

					if (!this.form.solveRemarks) {
						this.isUse = true

						wx.showToast({
							title: '请输入备注',
							icon: 'none'
						})
						return
					}
					if (!regex.test(this.form.solveRemarks)) {
						this.isUse = true

						wx.showToast({
							title: '请正确输入备注格式',
							icon: 'none'
						})
						return
					}
					if (this.fileListsCopy.length == 0) {
						this.isUse = true

						wx.showToast({
							title: '请上传图片',
							icon: 'none'
						})
						return
					}
					this.form.path = []
					for (var i = 0; i < this.fileListsCopy.length; i++) {
						if (this.fileListsCopy[i].path.indexOf(IMG_URL) >= 0) {
							this.form.path.push(this.fileListsCopy[i].path.split(IMG_URL)[1])

						} else {
							this.form.path.push(this.fileListsCopy[i].path)

						}
					}
					solveDefect(this.form).then(res => {
						if (res.code == '0') {
							uni.showToast({
								title: '操作成功',
								duration: 1500,
								mask: true
							})
							setTimeout(() => {
								uni.navigateBack({
									delta: 2 // 默认值是1，表示回退到上一页，如果要回退多级可以设置大于1的数值
								});
								// if (uni.getStorageSync('isWarm')) {
								// 	wx.removeStorageSync('isWarm');
								// 	uni.switchTab({
								// 		url: '/pages/order/jinggaoIndex',

								// 	})
								// } else {
								// 	if (uni.getStorageSync('userInfo').role == 'solve') {
								// 		uni.switchTab({
								// 			url: '/pages/order/index',
								// 			animationType: 'pop-in',
								// 			animationDuration: 200
								// 		})

								// 	} else if (uni.getStorageSync('userInfo').role == 'admin' || uni
								// 		.getStorageSync('userInfo').role == 'administrator') {
								// 		uni.switchTab({
								// 			url: '/pages/order/managerIndex',
								// 			animationType: 'pop-in',
								// 			animationDuration: 200
								// 		})
								// 	}
								// }
							}, 1000)


						} else {
							wx.showToast({
								title: res.msg,
								icon: 'none',
								duration: 2000
							})
							setTimeout(() => {
								this.isUse = true
								if (uni.getStorageSync('isWarm')) {
									wx.removeStorageSync('isWarm');
									uni.switchTab({
										url: '/pages/order/jinggaoIndex',

									})
								} else {
									if (uni.getStorageSync('userInfo').role == 'solve') {
										uni.switchTab({
											url: '/pages/order/index',
											animationType: 'pop-in',
											animationDuration: 200
										})

									} else if (uni.getStorageSync('userInfo').role == 'admin' || uni
										.getStorageSync('userInfo').role == 'administrator') {
										uni.switchTab({
											url: '/pages/order/managerIndex',
											animationType: 'pop-in',
											animationDuration: 200
										})
									}
								}
							}, 2000)
							this.isUse = true
						}
					}).finally(() => {
						setTimeout(() => {
							this.isUse = true

						}, 1300)

					})
				}

			},


		}

	};
</script>

<style scoped lang="scss">
	.bg {
		box-sizing: border-box;
		// padding:0rpx 50rpx;
		height: 100vh;
		background: #F5F6F8;

		.noboderbottom {
			border-bottom: none !important;
		}

		.infoItem {
			padding: 20rpx 0;
			display: flex;
			justify-content: space-around;
			flex-direction: column;
			border-bottom: 1rpx solid #b1aeae;

			.infoItem_label {
				width: 200rpx;
				font-family: Source Han Sans CN, Source Han Sans CN;
				font-weight: 500;
				font-size: 28rpx;
			}

			.infoItem_content {
				background: #FFFFFF;
				height: 80rpx;
				border-radius: 6rpx 6rpx 6rpx 6rpx;
				border: 2rpx solid #707070;
				flex-wrap: wrap;
				flex: 1;
				font-family: Source Han Sans CN, Source Han Sans CN;
				font-weight: 400;
				font-size: 28rpx;
				color: #262626;
			}

			input {
				height: 80rpx;
				box-sizing: border-box;
				padding: 20rpx;
			}
		}

		.line {
			height: 16rpx;
		}
	}

	.pImg {
		margin-top: 20rpx;
		width: 298rpx;
		height: 212rpx;
	}

	.hasFlex {
		display: flex;
		justify-content: space-between;
		flex-wrap: wrap;
	}

	.addBtn {
		margin-top: 30rpx;
		padding-bottom: 30rpx;
		line-height: 80rpx;

		.bts {
			text-align: center;
			width: 650rpx;
			height: 80rpx;
			margin: 0 auto;
			box-shadow: 0rpx 3rpx 6rpx 1rpx rgba(0, 0, 0, 0.16);
			border-radius: 12rpx 12rpx 12rpx 12rpx;
			font-family: Source Han Sans CN, Source Han Sans CN;
			font-weight: 500;
			font-size: 36rpx;

		}

		.edit {
			background: #5C7FF5;
			color: #FFFFFF;
		}

		.del {
			background: #FFFFFF;
			box-shadow: 0rpx 3rpx 6rpx 1rpx rgba(0, 0, 0, 0.16);
			border-radius: 12rpx 12rpx 12rpx 12rpx;
			border: 1rpx solid #707070;
			font-family: Source Han Sans CN, Source Han Sans CN;
			font-weight: 500;
			font-size: 36rpx;
			color: #2B2B2B;
		}
	}
</style>
<style scoped>
	.p30 {
		padding: 20rpx 30rpx;

	}

	.p50 {
		padding: 20rpx 50rpx;

	}

	.bgwhite {
		background: white;
		box-shadow: 0rpx 3rpx 6rpx 1rpx rgba(0, 0, 0, 0.16);
	}

	.bg>>>.uni-nav-bar-text {
		font-size: 35rpx;
	}

	.bg>>>.icon-del-box {
		/* display: none!important; */
		width: 40rpx;
		height: 40rpx;
		background-color: red;

	}

	.bg>>>.icon-del {
		width: 20rpx;
		height: 4rpx;
	}
</style>